/*
 * CodeDocFunktioner.cpp
 *
 * Created on: 18/03/2012
 * Author: Kimowich
 */

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <sstream>
#include "Codedoc.h"
#include "textContent.h"
#include "WordPack.h"
using namespace std;

fstream inout1;


Codedoc::Codedoc()
{

}

Codedoc::Codedoc(string Fn,bool ro, textContent *TC1)
{
	TC = TC1;
    filename = Fn;
    if(ro == 0)
    {
        load();
    }
    else
    {
        save();
    }
}

int Codedoc::save()
{
	
	int diffwords = TC->getWordCound();//number which will contain the result
	int numwords = TC->getPosCound();//number which will contain the result

	if(TC->getBin())
	{
		cout << "numwords" << numwords << " diffwords" << diffwords << endl;
		WordPack WP(filename.c_str(),numwords,diffwords);
		for(int i=0;i<numwords;i++)
		{
			WP.writeInt(TC->getPos(i));
		}
		for(int i=0;i<diffwords;i++)
		{
			WP.writeWord(TC->getListWord(i));
		}
		WP.close();
	}
	else
	{
		inout1.open(filename.c_str(), ios::out);
		if(inout1.fail())//tjek if theres a file named that!
		{
			cout << "Theres no file named that" << endl;
			cout << "Exit Program" << endl;
			return 0;
		}
		inout1 << "txt" << " " << numwords << " " << diffwords << " \n";
		for(int i=0;i<numwords;i++)
		{
			inout1 << TC->getPos(i) << " ";
		}
		inout1 << "\n";
		for(int i=0;i<diffwords;i++)
		{
			inout1 << TC->getListWord(i) << " ";
		}
		inout1.close();
	}
	return 0;
}

int Codedoc::load()
{
	WordPack WP(filename.c_str());
	int diffwords;//number which will contain the result
	int numwords;//number which will contain the result
	int i;
	int Result=0;
	string charstring;
	 
	int test;
	std::string str;
	if(WP.getBin())
	{
		TC->setBin(true);
		cout << "bin!!!" << " numpos=" << WP.getNumPos()<< endl;
		for(int j=0;j<(WP.getNumPos());++j)
		{
			test = WP.getInt();
			TC->addCode(test);
			//cout << "getint " << test << " j=" << j << endl;
		}
		for(int j=0;j<(WP.getNumWords());++j)
		{
			TC->addListWord(WP.getWord());
		}
		WP.close();
	}
	else
	{
		TC->setBin(false);
		inout1.open(filename.c_str(), ios::in);
		if(inout1.fail())
		{
			cout << "Theres no file named that" << endl;
			cout << "Exit Program" << endl;
			return 0;
		}
		inout1 >> charstring >> numwords >> diffwords; 
		i = 0;
		while(i<numwords)
		{
			inout1 >> Result;
			TC->addCode(Result);
			i++;
		}
		i=0;
		while(i<diffwords)
		{	
			inout1 >> charstring;
			TC->addListWord(charstring);
			i++;
		}
		inout1.close();
	}
	return 0;
}
